package fsfileserver;
import java.util.ArrayList;
import java.rmi.*;
import java.util.Random;
import FsInterfaces.*;
import java.net.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class FileServer extends java.rmi.server.UnicastRemoteObject implements FsInterfaces.IFileServer {

    Registry registry;
    ArrayList<File> fileList = new ArrayList();
    FileLoader fileLoader = new FileLoader();
    private int testRandom=1000;
    private boolean doTest=false;

    public void setTestRandom(int a, boolean b){
        this.testRandom=a;
        this.doTest=b;
    }

    public static void main(String[] args) throws Exception{
        FileServer fs = new FileServer(args[0], args[1], args[2]);
    }
    
    public FileServer(String name, String port, String path) throws RemoteException{

        String host;
        try{
            host = (InetAddress.getLocalHost()).toString();
            fileList = fileLoader.LoadFile(path);
        }
        catch (Exception ex){
            throw new RemoteException("Cannot find address.");
        }

       System.out.println("Starting server: '"+name+"' @ "+host+":"+port);
       //creating server and binding to registry
       try{
            registry = LocateRegistry.createRegistry(Integer.parseInt(port));
            registry.rebind(name, this);
        }
        catch(RemoteException e){
            throw e;
        }
    }

    public int CheckFile(String aTitle) throws RemoteException{
        System.out.println("Searching for file: "+aTitle);
        for(File a:fileList){
            if(a.getName().equals(aTitle)){
                System.out.println("File found. It needs "+a.getBandwidth()+" KB/s to download.");
                int bandWidthAvailable = getMockBandWidth();
                System.out.print("Checking bandwidth against requirements...");
                if (a.getBandwidth()<bandWidthAvailable){
                   System.out.println("OK.");
                   return bandWidthAvailable;
                }
                else{
                    System.out.println("Not OK ... returning 0");
                    return 0;
                }
            }
        }
        System.out.println("file not found, returning 0");
        return 0;
    }
    
    //makes a random bandwidth between 0-5000 unlesss doTest boolean is true
    private int getMockBandWidth(){
        if(doTest==true){ //for test purposes
            System.out.println("Testbandwidth: "+testRandom);
            return testRandom;
        }
        else{
            Random rand = new Random();
            int temp = rand.nextInt(5000);
            System.out.println("Calculating MockBandWidth: "+temp);
            return temp;
        }
    }
}
